package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.system.domain.SysOperLog;
import com.ruoyi.system.domain.vo.MongoLogSearchVo;
import com.ruoyi.system.service.IMongoLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.List;

@Service
public class MongoLogService implements IMongoLogService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void insert(SysOperLog operLog, String table) {
        JSONObject jsonObject = JSON.parseObject(operLog.getOperParam());
        jsonObject.put("table", table);
        jsonObject.put("operName", operLog.getOperName());
        jsonObject.put("operTime", System.currentTimeMillis());
        mongoTemplate.insert(jsonObject, "log");
    }

    @Override
    public List<LinkedHashMap> list(MongoLogSearchVo searchVo) {
        Query query = new Query(Criteria
                .where("id").is(searchVo.getId())
                .and("table").is(searchVo.getTable()));
        query.with(Sort.by(Sort.Direction.DESC, "_id", "operTime"));
        List<LinkedHashMap> list = mongoTemplate.find(query, LinkedHashMap.class, "log");
        return list;
    }
}
